package com.ruyuan.o2o.groupbuy.code.admin.service;

import com.ruyuan.o2o.groupbuy.code.admin.dao.CodeDao;
import com.ruyuan.o2o.groupbuy.code.model.CodeModel;
import com.ruyuan.o2o.groupbuy.code.service.CodeService;
import com.ruyuan.o2o.groupbuy.code.vo.CodeVO;
import com.ruyuan.o2o.groupbuy.common.BeanMapper;
import com.ruyuan.o2o.groupbuy.common.TimeUtil;
import com.ruyuan.o2o.groupbuy.image.service.ImageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Random;


/**
 * 处理券码服务的增删改查service组件
 *
 * @author ming qian
 */
@Service(version = "1.0.0", interfaceClass = CodeService.class, cluster = "failfast", loadbalance = "roundrobin")
@Slf4j
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeDao codeDao;

    @Reference(version = "1.0.0", interfaceClass = ImageService.class,
            cluster = "failfast", loadbalance = "roundrobin")
    private ImageService imageService;

    /**
     * 生成券码
     *
     * @param codeVO
     */
    @Override
    public void save(CodeVO codeVO) {
        CodeModel codeModel = new CodeModel();
        BeanMapper.copy(codeVO, codeModel);

        //  调用第三方二维码组件生成二维码
        log.info("二维码生成完成");
        String imagePath = imageService.uploadImage();
        log.info("二维码上传完成");
        codeModel.setQrCodeImg(imagePath);

        //  模拟随机生成数字码
        codeModel.setDigitalCode(new Random().nextInt());
        codeModel.setCodeStatus(0);
        codeModel.setCreateTime(TimeUtil.format(System.currentTimeMillis()));
        codeModel.setUpdateTime(TimeUtil.format(System.currentTimeMillis()));

        codeDao.save(codeModel);
    }

    /**
     * 根据id查询券码
     *
     * @param userId 用户id
     * @param payId  支付id
     * @return
     */
    @Override
    public CodeVO findById(Integer userId, Integer payId) {
        CodeModel codeModel = codeDao.findById(userId, payId);
        CodeVO codeVO = new CodeVO();
        BeanMapper.copy(codeModel, codeVO);
        return codeVO;
    }

    /**
     * 核销券码
     *
     * @param codeVO
     */
    @Override
    public void writeOffCode(CodeVO codeVO) {
        CodeModel codeModel = new CodeModel();
        BeanMapper.copy(codeVO, codeModel);

        //  核销二维码 or 核销数字码
        codeModel.setCodeStatus(1);
        codeModel.setUpdateTime(TimeUtil.format(System.currentTimeMillis()));

        codeDao.writeOffCode(codeModel.getId(), codeModel.getCodeStatus(), codeModel.getUpdateTime());
    }

}
